import { defineTool, exec, run } from "@/utils.js"

const ignoredFiles = ["pnpm-lock.yaml"]

async function getChangedFiles(hasStaged: boolean): Promise<string[]> {
  const excludeClause = ignoredFiles.map((f) => `":(exclude)${f}"`).join(" ")
  const cmd = `git ${hasStaged ? "diff --cached" : "diff"} --name-only -- . ${excludeClause}`
  const output = (await exec(cmd)).toString("utf8").trim()
  return output ? output.split("\n").filter(Boolean) : []
}

export async function diff(): Promise<string> {
  const hasStaged = (await run("git diff --cached --quiet")) !== 0
  const files = await getChangedFiles(hasStaged)
  const excludeClause = ignoredFiles.map((f) => `":(exclude)${f}"`).join(" ")
  const cmd = `git ${hasStaged ? "diff --cached" : "diff"} --no-ext-diff -- . ${excludeClause}`
  const diffOutput = (await exec(cmd)).toString("utf8").trim()

  let result = ""
  if (files.length > 0) {
    const stageLabel = hasStaged ? "暂存区" : "工作区"
    result += `更改的文件 (${stageLabel}):\n`
    result += files.map((f) => `  ${f}`).join("\n")
    result += "\n\n"
  }
  result += diffOutput || "No changes"
  return result
}

export default defineTool({
  name: "git_diff",
  description: "查看工作区或暂存区的更改",
  async callback(_extra) {
    return { content: [{ type: "text", text: (await diff()) || "No changes" }] }
  },
})
